var express = require("express");
var router = express.Router();
const WebSocket = require("ws");
let { imgsModel, petModel, dictorModel,addressBookModel } = require("../../models/db");
let clients = [];
const wss = new WebSocket.Server({ port: 8080 });
wss.on("connection", function (socket) {
  console.log("WebSocket连接成功");
  socket.on("message", function (message) {
    console.log("接收到户端发送的消息：" + message);
    //每个客户端都存上自己发来的phone做为唯一的id
    //连接上后就压进数组
    clients.push({ id: message, ws: socket });
    
  });
  // 监听连接关闭事件
  socket.on("close", function() {
    console.log("WebSocket连接已关闭");
  });
});
// 当有人发送消息的时候
router.post('/sendMsg', (req, res) =>{
  //前端传过来的数据,otherId是当前要接受消息的人的id,message是消息主体,_id是当前发送消息的人的id,otherName是当前发送消息人的项目
    let {otherId,message,_id,otherName} = req.body
    console.log(otherId);
    const datalist = {
      _id,
      message,
      otherName,
    }
    const Medatalist = {
      _id,
      message,
    }
    console.log(datalist);
    //循环遍历     找到你要发送的人  他的id  就发送
    clients.forEach((ele) =>{
      console.log('eleid',ele.id);
      console.log(otherId);
      if(otherId.slice(1,otherId.length-1)==ele.id){
        ele.ws.send(JSON.stringify(datalist));
      } 
    });
    //发送给自己客户端的数据
    res.send(Medatalist)
  })
//获取我们的通讯录
router.get('/getAddressBooks',async function (req, res, next) {
  let {_id} = req.query
  let data = await addressBookModel.find({uid:_id})
  res.send({
    code:200,
    data
  });
});
/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});
//轮播图
router.get("/imgs_show", async function (req, res, next) {
  let data = await imgsModel.find();
  res.send({
    code: 200,
    data,
  });
});
//宠物
router.get("/pet_show", async function (req, res, next) {
  let data = await petModel.find();
  res.send({
    code: 200,
    data,
  });
});
//医生
router.get("/doctor_show", async function (req, res, next) {
  let { _id, doctorName } = req.query;
  let obj = {};
  if (_id) {
    obj._id = _id;
  }
  if (doctorName) {
    doctorName = new RegExp(doctorName);
    obj.doctorName = doctorName;
  }
  let data = await dictorModel.find(obj);
  res.send({
    code: 200,
    data,
  });
});
module.exports = router;
